/*
 * SdlSurfacePtr.cpp
 *
 *  Created on: 2014年4月27日
 *      Author: zhengchuanjiang
 */

#include "SdlSurfacePtr.h"

namespace sdl
{

SurfacePtr::SurfacePtr():
        m_surface(),
        m_texture(),
        m_render()
{
}

SurfacePtr::~SurfacePtr()
{
    cleanup();
}

SurfacePtr::SurfacePtr(SDL_Surface* surface):
        m_surface(),
        m_texture(),
        m_render()
{

}

SDL_Surface* SurfacePtr::get() const
{
    return m_surface;
}

void SurfacePtr::reset()
{
    cleanup();
}

void SurfacePtr::reset(SDL_Surface* surface)
{
    if (m_surface == surface)
    {
        return;
    }

    cleanup();

    m_surface = surface;
}

SurfacePtr::operator bool() const
{
    return (m_surface != NULL);
}

void SurfacePtr::cleanup()
{
    if (m_surface)
    {
        SDL_FreeSurface(m_surface);
        m_surface = NULL;
    }

    cleanTexture();
}

void SurfacePtr::cleanTexture()
{
    if (m_texture)
    {
        SDL_DestroyTexture(m_texture);
        m_texture = NULL;
    }

    m_render = NULL;
}

SDL_Texture* SurfacePtr::update(SDL_Renderer* render)
{
    if (render == NULL)
    {
        cleanTexture();
        return m_texture;
    }

    if (render != m_render)
    {
        cleanTexture();
    }

    m_texture = SDL_CreateTextureFromSurface(render, m_surface);
    m_render = render;

    return m_texture;
}

SDL_Texture* SurfacePtr::getTexture()
{
    return m_texture;
}

bool SurfacePtr::getSize(int& w, int& h)
{
    if (!m_surface)
    {
        return false;
    }

    w = m_surface->w;
    h = m_surface->h;

    return true;
}






} /* namespace sdl */
